package com.grm.direct;

import com.grm.util.RabbitMqUtils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class Consumer {
	public static void main(String[] args) {
		getMessage();
	}

	public static void getMessage() {
		try {
			//建立连接
			Connection connection = RabbitMqUtils.getConnection();
			
			//建立通道
			Channel channel = connection.createChannel();

			//通道绑定交换机
			String exchange = "canal.exchange";
			channel.exchangeDeclare(exchange,"direct");

			//临时队列
			String queueName = channel.queueDeclare().getQueue();

			//基于routing key绑定交换机和队列
			channel.queueBind(queueName,exchange,"canal.routing.key");

			//消费消息
			channel.basicConsume(queueName,true,new DefaultConsumer(channel){
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
					log.info("canal consumer message = {}",new String(body));
				}
			});
	        //不关闭连接跟通道
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
